class Compiler {
  constructor(vm) {
    this.vm = vm;
    this.el = vm.$el;
    this.compile(this.el);
  }

  compile (el) {
    // el.childNodes 是一个伪数组
    let childNodes = el.childNodes;
    Array.from(childNodes).forEach(node => {
      // console.log('node: ', node);
      if (this.isTextNode(node)) {
        // 解析插值表达式
        this.compileText(node);
      } else if (this.isElementNode(node)) {
        // 解析指令
        this.compileElement(node)
      }

      if(node.childNodes && node.childNodes.length) {
        this.compile(node);
      }
    })
  }

  compileElement (node) {
    Array.from(node.attributes).forEach(attr => {
      let attrName = attr.name;
      if (this.isDirective(attrName)) {
        attrName = attrName.substr(2);
        let key = attr.value;
        this.update(node, this.vm[key], attrName, key)
      }
    })
  }

  update (node, value, attrName, key) {
    if (this.isEventDirective(attrName)) {
      // v-on 事件绑定
      // debugger;
      console.log('attrName:', key);
      const eventyType = attrName.split(':')[1];
      debugger;
      this.eventBind(node, eventyType, this.vm[key], key);
    } else {
      let updateFn = this[attrName + "Updater"];
      updateFn.call(this, node, value, key);
    }
  }

  /** v-text */
  textUpdater (node, value, key) {
    node.textContent = value;
    new Watcher(this.vm, key, newValue => {
      node.textContent = newValue;
    })
  }

  /** v-model */
  modelUpdater (node, value, key) {
    node.value = value;
    new Watcher(this.vm, key, newValue => {
      node.value = newValue;
    })

    node.addEventListener('input', e => {
      this.vm[key] = e.target.value
    })
  }

  /** v-html */
  htmlUpdater(node, value, key) {
    node.innerHTML = value;
    new Watcher(this.vm, key, newValue => {
      node.innerHTML = newValue;
    })
  }

  /** v-on */
  eventBind(node, eventType, value, key) {
    node.addEventListener(eventType, value);

    new Watcher(this.vm, key, newValue => {
      node.removeEventListener(eventType, value);
      value = newValue;
      node.addEventListener(eventType, value);
    })
  }

  compileText (node) { 
    let regx = /\{\{(.+?)\}\}/;
    let value = node.textContent;
    // console.log('value: ', value);
    if (regx.test(value)) {
      let key = RegExp.$1.trim();
      node.textContent = value.replace(regx, this.vm[key]);

      new Watcher(this.vm, key, newValue => {
        node.textContent = newValue;
      })
    }
    
  }

  // 判断是否是 v-on 指令
  isEventDirective(attrName) {
    return attrName.startsWith('on');
  }

  isDirective (attrName) {
    return attrName.startsWith('v-')
  }

  isTextNode (node) {
    return node.nodeType === 3;
  }

  isElementNode (node) {
    return node.nodeType === 1;
  }
}